/*
Copyright (c) 2010 Embedded Systems and Pervasive Laboratory, Federal
University of Campina Grande, Brazil, Angelo Perkusich, Mirko Perkusich,
Taciana Rached

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN  THE SOFTWARE.
*/

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)

{
    /** Instantiate Picture Flow */
    pFlow = new PictureFlow();

    /** set main window */
    setMainWindow();

    /** set up connections */
    setupConnections();
}

void MainWindow::setupConnections()
{
    QObject::connect(&btManager, SIGNAL(dataReceived(QByteArray)), this, SLOT(classifyData(QByteArray)));
    QObject::connect(connectButton, SIGNAL(clicked()), &btManager, SLOT(connect()));
    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    QObject::connect(&btManager, SIGNAL(connected()), this, SLOT(loadContactsInfo()));
    QObject::connect(&btManager, SIGNAL(connected()), this, SLOT(setWindow()));
    QObject::connect(&parser, SIGNAL(attentionLevel(int)), this, SLOT(attentionReceived(int)));
    QObject::connect(&parser, SIGNAL(meditationLevel(int)), this, SLOT(meditationReceived(int)));
}

void MainWindow::setWindow()
{
    /** Set Picture Flow properties */
    pFlow->setSlideSize(QSize(300, 240));
    pFlow->resize(800, 300);
    pFlow->setCenterIndex(0);
    pFlow->setReflectionEffect(PictureFlow::NoReflection);
    pFlow->setBackgroundColor(Qt::black);
    pFlow->show();

    /** Set Widgets visibility*/
    connectButton->setVisible(false);
    quitButton->setVisible(false);
    pFlow->setVisible(true);
    medProgBar->setVisible(true);
    aProgBar->setVisible(true);
    pFlow->showNext();
    pFlow->showNext();
}

void MainWindow::loadContactsInfo()
{
    /** Contacts manager for maemo 5*/
    QContactManager* myContactManager = new QContactManager("maemo5");

    /** List with all contacts */
    contacts = myContactManager->contacts();
    for(int i = 0; i < contacts.count(); i++){
        QContactThumbnail tInfo = contacts.at(i).detail(QContactThumbnail::DefinitionName);
        if (tInfo.isEmpty())
            /** load a Default Image */
            pFlow->addSlide(QImage(":/defaultImage.jpg"));
        else
            pFlow->addSlide(tInfo.thumbnail());

        pFlow->addSlideCaption(contacts.at(i).displayLabel());
    }
}

void MainWindow::classifyData(QByteArray data)
{
    /* Classify Data */
    qDebug() << data.toHex();
    for(int i = 0; i < data.size(); i++)
        parser.parseByte(data.at(i));
}

void MainWindow::meditationReceived(int inMedLevel){
    medProgBar->setValue(inMedLevel);
    if (inMedLevel > 80)
        makeCall();
}

void MainWindow::attentionReceived(int inALevel){
    aProgBar->setValue(inALevel);
    if (inALevel > 0 && inALevel < 30)
        pFlow->showPrevious();
    else if (inALevel > 70)
        pFlow->showNext();
}

void MainWindow::makeCall()
{
    /** get phone number from the contact currently at the center of the screen */
    QContactPhoneNumber phoneNumber = contacts.at(pFlow->centerIndex()).detail(QContactPhoneNumber::DefinitionName);
    /** phone number to be called */
    QString number = phoneNumber.number();
    qDebug() << "Phone number: " << number;

    QProcess *process = new QProcess();

    /** command to make a phone call on maemo 5 */
    QString command = QString("/usr/bin/run-standalone.sh dbus-send ") +
        QString("--system --type=method_call --print-reply ") +
        QString("--dest=com.nokia.csd.Call /com/nokia/csd/call ") +
        QString("com.nokia.csd.Call.CreateWith ") +
        QString("string:\"") + number + QString("\" ") +
        QString("uint32:0");

    /** command to turn loud speaker on on maemo 5 */
    QString command2 = QString("/usr/bin/run-standalone.sh dbus-send ") +
        QString("--type=method_call --dest=com.nokia.osso_hp_ls_controller ") +
        QString("/com/nokia/osso_hp_ls_controller com.nokia.osso_hp_ls_controller.") +
        QString("loudspeaker.force_loudspeaker_off");

    qDebug() << "Phone number: " << command;

    qDebug() << "Loud speaker: " << command2;
    /** make the phone call */
    process->start(command);
    /** turn loudspeaker on */
    process->start(command2);
    /** show application window full screen */
    this->showFullScreen();
}

void MainWindow::setMainWindow()
{
    /** Progress Bars and Buttons Layout */
    QHBoxLayout* barsLayout = new QHBoxLayout();
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    /** Set Buttons */
    connectButton = new QPushButton(this);
    connectButton->setText("Connect");
    quitButton = new QPushButton(this);
    quitButton->setText("Quit");
    /** Set Buttons Layout*/
    buttonLayout->addWidget(connectButton);
    QSpacerItem* horizontalSpacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    buttonLayout->addItem(horizontalSpacer);
    buttonLayout->addWidget(quitButton);

    /** Set Vertical Layout */
    QWidget* layoutWidget = new QWidget(this);
    layoutWidget->setGeometry(0, 0, 800, 400);
    QVBoxLayout* layout = new QVBoxLayout(layoutWidget);
    layout->setGeometry(QRect(0, 50, 800, 300));
    layout->addLayout(buttonLayout);
    /** add and set PictureFlow widget */
    layout->addWidget(pFlow);
    pFlow->setVisible(false);
    /** add meditation and attention progress bars */
    medProgBar = new QProgressBar(this);
    barsLayout->addWidget(medProgBar);
    medProgBar->setVisible(false);
    aProgBar = new QProgressBar(this);
    barsLayout->addWidget(aProgBar);
    aProgBar->setVisible(false);
    layout->addLayout(barsLayout);
}
